<template>
    <div class="code-view">
        <el-dialog
                title="JSON视图"
                :visible.sync="dialogVisible"
                width="600px">
             <pre>{{codeData}}</pre>
            <input type="text" id="code" style="position: absolute; z-index: -1; opacity: 0">
             <span slot="footer" class="dialog-footer">
                <el-button @click="copyToClipboard">复 制</el-button>
                <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
              </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
  name: 'codeView',
  props: {
    codeData: {
      required: true
    }
  },
  data() {
    return {
      dialogVisible: false
    }
  },
  methods: {
    open() {
      this.dialogVisible = true
    },
    async copyToClipboard() {
      try {
        const inputElement = document.querySelector('#code'); // 选中元素
        inputElement.value = JSON.stringify(this.codeData)
        inputElement.select(); // 选中输入框
        document.execCommand('copy'); // 进行复制
      } catch (err) {
        console.log(err)
        this.$TZmessage.error('复制失败')
      }
      this.dialogVisible = false
    }
  }
}
</script>

<style lang="scss" scoped>
    .code-view {
        pre {
            font-family: Consolas, Inconsolata, Courier, monospace;
            font-size: 14px;
            line-height: 22px;
            color: #abb2bf;
            background: #282c34;
            max-height: 50vh;
            overflow: auto;
            padding: 20px;
        }
        ::v-deep .el-dialog__body {
            padding: 0;
        }
    }
</style>